<template>
	<view class="container pt_12 pb_69 plr_12">
		<view class="pt_230" v-if="!isLogin">
			<Empty type="logout" />
		</view>
		<template v-else-if="!permission">
			<NoPermission :requestCount="requestCount" :ossUrl="ossUrl" :basicUnserInfo="basicUnserInfo" />
		</template>
		<template v-else>
			<view class="fx aic jcb fz_12">
				<view class="fx aic">
					<uni-icons custom-prefix="iconfont" type="icon-baozhang-1" color="#999" size="28rpx"></uni-icons>
					<text class="ml_6">正品保障</text>
				</view>
				<view class="fx aic">
					<uni-icons custom-prefix="iconfont" type="icon-baozhang-2" color="#999" size="28rpx"></uni-icons>
					<text class="ml_6">极速发货</text>
				</view>
				<view class="fx aic">
					<uni-icons custom-prefix="iconfont" type="icon-wuliu" color="#999" size="28rpx"></uni-icons>
					<text class="ml_6">配送全国</text>
				</view>
				<view class="fx aic">
					<uni-icons custom-prefix="iconfont" type="icon-baozhang-3" color="#999" size="28rpx"></uni-icons>
					<text class="ml_6">售后无忧</text>
				</view>
			</view>
			<view class="fx aic jcb pt_20 pb_8">
				<view class="fz_12">
					全部商品 {{totalNum}}
				</view>
				<button class="custom_btn default width_56 lh_25 br_21 fz_12" style="background-color: #F5F5F5;"
					@click="handleEdit" v-if="!isEdit">编辑</button>
				<button class="custom_btn default width_56 lh_25 br_21 fz_12" style="background-color: #F5F5F5;"
					@click="isEdit = false" v-else>完成</button>
			</view>
			<view class="list_item_box br_8 bc_fff" v-for="item,index in dataList" :key="index">
				<checkbox-group @change="handleChangeGoodsSelectAll($event,item)">
					<label class="fx aic">
						<checkbox :value="item.id" :checked="isSelectItemAll(item)" style="transform: scale(0.7);"
							class="pl_16 checkbox round red" color="#F08519" activeBackgroundColor="#F08519" />
						<view class="fx aic bob_1 boc_grey ptb_12 pl_12 fx_1 flow_h">
							<uni-icons custom-prefix="iconfont" type="icon-shangdian" color="#999" size="32rpx"
								v-if="item.brandId"></uni-icons>
							<view class="ml_4 fx_1 flow_h">{{item.brandName}}</view>
						</view>
					</label>
				</checkbox-group>
				<checkbox-group @change="handleChangeGoodsSelect($event,item)">
					<label class="p_12 fx aic" v-for="item1,index1 in item.list" :key="item1.id">
						<checkbox :value="item1.id" :checked="item1.checked" style="transform: scale(0.7);"
							class="ass pl_4 pr_10 mt_32 checkbox round red" color="#F08519"
							activeBackgroundColor="#F08519" />
						<u-swipe-action>
							<u-swipe-action-item :options="options1" @click="handleDelete([item1.id])">
								<view class="swipe-action">
									<view class="fx_1 fx flow_h" @longpress="handleDelete([item1.id])"
										@click="()=>isEdit?{}:handleDetail(item1)">
										<CustomImage width="160rpx" height="160rpx" radius="8rpx"
											:src="item1.specificationImageUrl||item1.coverImageUrl">
										</CustomImage>
										<view class="ml_12 fx_1 flow_h">
											<view class="fe_2 lh_18 height_36">
												{{item1.productName||''}}
											</view>
											<view class="height_24" @click.stop="">
												<view class="ib_fx fx_nw flow_h aic mt_4 height_20 plr_8 br_21 fc_666"
													style="background-color: #f2f2f2;max-width:calc(100% - 32rpx)"
													v-if="item1.ruleValueStr" @click="handleGoodsInfo(item1)">
													<view class="fe">
														{{item1.ruleValueStr}}
													</view>
													<view class="fx_sh ml_4">
														<u-icon name="arrow-down" color="#666" size="24rpx"></u-icon>
													</view>
												</view>
											</view>
											<view class="fx fx_nw aic jcb mt_12" @click.stop="">
												<view class="fc_zhured fz_16 fb">
													<text class="fz_10">￥</text>
													{{item1.price}}
												</view>
												<u-number-box :max="100" :asyncChange="true" :value="item1.productNum"
													buttonSize="48rpx" color="#000" bgColor="#fff"
													@focus="handleFocusNum($event,item1)"
													@change="handleChangeNum($event,item1)"
													@blur="handleBlurNum($event,item1)"></u-number-box>
											</view>
										</view>
									</view>
								</view>
							</u-swipe-action-item>
						</u-swipe-action>
					</label>
				</checkbox-group>
			</view>
			<view class="list_item_box disabled_wrap br_8 bc_fff" :class="isUnfold?'unfold':''"
				v-if="invalidList&&invalidList.length">
				<view class="fx aic jcb bob_1 boc_grey p_12" @click="handleFold">
					<view class="fx aic">
						失效商品
						<view class="ml_4 arrow_icon pr" v-if="unfoldAble">
							<u-icon name="arrow-down" color="#333" size="32rpx"></u-icon>
						</view>
					</view>
					<view class="fx aic" @click.stop="handleClear">
						<u-icon name="trash" color="#FE0000" size="32rpx"></u-icon>
						<view class="ml_4 fz_12 fc_zhured">
							清空
						</view>
					</view>
				</view>
				<view class="disabled_lis_box" :style="[disabledBoxStyle]">
					<view class="p_12 fx aic" v-for="item,index in invalidList" :key="index1">
						<view class="fz_12 fc_999 pl_4 pr_16">
							失效
						</view>
						<view class="fx_1 fx flow_h">
							<view class="pr">
								<CustomImage width="160rpx" height="160rpx" radius="8rpx" :src="item.coverImageUrl">
								</CustomImage>
								<view class="pa t_0 l_0 r_0 b_0 br_4" style="background: rgba(0,0,0,0.4);"></view>
							</view>
							<view class="ml_12 fx_1 flow_h">
								<view class="fe_2 lh_18 height_36 fc_ccc">
									{{item.productName||''}}
								</view>

								<image class="width_80 height_50" style="margin-top: 16rpx;" slot="active-icon"
									src="@/static/images/shixiaoicon.png"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="pf l_0 r_0 b_0 ptb_10 plr_12 box_shadow bc_fff fx aic jcb zbi_10">
				<checkbox-group @change="handleSelectAll">
					<label class="fx aic">
						<checkbox :checked="isSelectAll()" style="transform: scale(0.7); "
							class="pr_4 checkbox round red" />
						<view class="fz_12">
							<view>
								全选
							</view>
							<view v-if="!isEdit">
								合计：<text class="fc_zhured">￥{{totalPrice}}</text>
							</view>
						</view>
					</label>
				</checkbox-group>
				<button class="custom_btn primary width_94 lh_36 fz_14 br_24" v-if="isEdit"
					@click="handleDelete">删除</button>
				<button class="custom_btn primary width_94 lh_36 fz_14 br_24" v-else @click="handleBuy">结算</button>
			</view>
		</template>
		<GoodsWindow :data="dataInfo" :num="dataNum" :visible="goodsPopShow" :safeAreaInsetBottom="false"
			@close="handleCloseGoodsWindow" />
	</view>
</template>

<script>
	import CustomImage from '@/components/Image'
	import GoodsWindow from '@/components/goods/GoodsWindow'
	import Empty from '@/components/Empty'
	import permissionMixin from '@/mixins/permission.js'
	import NoPermission from "@/components/noPermission.vue"
	import api from '@/service/config/api.js'
	export default {
		mixins: [permissionMixin],
		components: {
			CustomImage,
			GoodsWindow,
			Empty,
			NoPermission
		},
		data() {
			return {
				goodsPopShow: false, // 规格弹窗
				isUnfold: false,
				rectHeight: 0,
				boxHeight: 0,
				unfoldAble: false,
				isEdit: false,
				pb: uni.upx2px(184),
				ids: [],
				dataList: [],
				invalidList: [

				], // 失效商品
				isFocus: false, // 数量步进器是否聚焦
				dataInfo: {}, // 商品详情
				dataId: '', // 选择商品购物车id
				dataNum: 1, // 选择商品数量
				goodsType: 1,
				isLogin: !!uni.getStorageSync('token'),
				options1: [{
					text: '删除',
					style: {
						backgroundColor: '#F08519',
					}
				}]
			};
		},
		computed: {
			disabledBoxStyle() {
				return {
					height: this.unfoldAble ? (this.boxHeight + 'px') : 'auto'
				}
			},
			totalNum() {
				return this.dataList.reduce((num, item) => {
					return num + item.list.length
				}, 0)
			},
			isSelectItemAll() {
				return item => item.list.every(item1 => item1.checked)
			},
			isSelectAll() {
				return () => this.dataList.every(item => item.list.every(item1 => item1.checked))
			},
			totalPrice() {
				return this.dataList.reduce((num, item) => {
					return this.$utils.floatAdd(num, item.list.filter(item => item.checked).reduce((num1,
						item1) => {
						return this.$utils.floatAdd(num1, this.$utils.floatMul(item1.price || 0, item1
							.productNum * 1))
					}, 0))
				}, 0)
			}
		},
		onLoad() {
			setTimeout(() => {
				this.$nextTick(() => {
					setTimeout(() => {
						uni.createSelectorQuery().in(this).select('.disabled_lis_box')
							.boundingClientRect(
								data => {
									if (data) {
										this.rectHeight = data.height
										if (data.height > uni.upx2px(416)) {
											this.unfoldAble = true
											this.boxHeight = uni.upx2px(416)
										}
									}
								}).exec()
					})
				}, 100)
			}, 1000)
		},
		onShow() {
			if (this.isLogin)
				this.getData()
		},
		methods: {
			getData() {
				this.$utils.loading()
				api.post('/goods/api/ShoppingCart/findShoppingCartProducts', {
					ids: this.ids
				}).then(res => {
					this.invalidList = []
					if (res.data && res.data.length) {
						this.dataList = res.data.reduce((arr, item) => {
							if (item.ruleValue) {
								const ruleValue1 = JSON.parse(item.ruleValue)
								if (ruleValue1 && ruleValue1.length) {
									item.ruleValueStr = ruleValue1.map(item => item.value).join(';')
								}
							}
							item.checked = false
							if (item.invalid) {
								this.invalidList.push(item)
							} else {
								const listItem = arr.find(item1 => item1.brandId === item.brandId)
								if (listItem) {
									listItem.list.push(item)
								} else {
									arr.push({
										brandName: item.brandName,
										brandId: item.brandId,
										list: [item]
									})
								}
							}
							return arr
						}, [])
					} else {
						this.dataList = [];
					}
				})
			},
			handleFold() {
				if (!this.unfoldAble) return
				this.isUnfold = !this.isUnfold
				this.boxHeight = this.isUnfold ? this.rectHeight : uni.upx2px(416)
			},
			handleEdit() {
				this.isEdit = !this.isEdit
			},
			handleFocusNum() {
				this.isFocus = true
			},
			handleBlurNum({
				value,
				name
			}, item) {
				this.isFocus = false
				this.handleChangeNum({
					value,
					name
				}, item)
			},
			handleChangeNum({
				value
			}, item) {
				if (this.isFocus) return
				this.$utils.loading()
				api.post('/goods/api/ShoppingCart/updateShoppingCart', {
					id: item.id,
					productNum: value
				}).then(res => {
					this.$set(item, 'productNum', value * 1)
					console.log(res)
				})
			},
			handleChangeGoodsSelect(e, item) {
				const {
					value
				} = e.detail
				console.log('value----', value)
				item.list.forEach(item1 => {
					if (value.includes(item1.id)) {
						this.$set(item1, 'checked', true)
					} else {
						this.$set(item1, 'checked', false)
					}
				})
				const isSelectItemAll = this.isSelectItemAll(item)
				if (isSelectItemAll) {
					this.$set(item, 'checked', true)
				} else {
					this.$set(item, 'checked', false)
				}
			},
			handleChangeGoodsSelectAll(e, item) {
				const {
					value
				} = e.detail
				console.log('valueAll----', value)
				if (item.checked) {
					this.$set(item, 'checked', false)
					item.list.forEach(item1 => {
						this.$set(item1, 'checked', false)
					})
				} else {
					this.$set(item, 'checked', true)
					item.list.forEach(item1 => {
						this.$set(item1, 'checked', true)
					})
				}
				// const isSelectItemAll = this.isSelectItemAll(item)
				// item.list.forEach(item1 => {
				// 	if (isSelectItemAll && value.includes(item.id)) {
				// 		this.$set(item1, 'checked', false)
				// 	} else if (value.includes(item.id)) {
				// 		this.$set(item1, 'checked', true)
				// 	}
				// })
			},
			handleSelectAll() {
				const isSelectAll = this.isSelectAll()
				console.log('isSelectAll', isSelectAll)
				this.dataList.forEach(item => {
					item.list.forEach(item1 => {
						this.$set(item1, 'checked', isSelectAll ? false : true)
					})
				})
			},
			handleDelete(idsArr) {
				const ids = (idsArr && idsArr.length) ? idsArr : this.dataList.reduce((arr, item) => {
					return [...arr, ...item.list.filter(item1 => item1.checked).map(item1 => item1.id)]
				}, [])
				if (!ids.length) return this.$utils.showToast('请选择商品')
				uni.showModal({
					title: '提示',
					content: `确认要删除这${ids.length}件商品吗？`,
					confirmColor: '#F08519',
					cancelColor: '#999999',
					confirmText: '确定',
					cancelText: '我再想想',
					success: res => {
						if (res.confirm) {
							this.$utils.loading()
							api.post('/goods/api/ShoppingCart/deleteShoppingCart', ids).then(res => {
								this.$utils.showToast('已删除！')
								this.getData()
							})
						}
					}
				})
			},
			handleDetail(item) {
				uni.navigateTo({
					url: '/pages/goods/pages/detail?id=' + item.productId
				})
			},
			handleClear() {
				uni.showModal({
					title: '提示',
					content: `确认要清空失效商品吗？`,
					confirmColor: '#F08519',
					cancelColor: '#999999',
					confirmText: '确定',
					cancelText: '我再想想',
					success: res => {
						if (res.confirm) {
							this.$utils.loading()
							api.post('/goods/api/ShoppingCart/clearInvalid').then(res => {
								this.$utils.showToast('已清空！')
								this.getData()
							})
						}
					}
				})
			},
			handleGoodsInfo(item) {
				this.$utils.loading()
				api.get('/goods/api/product/info', {
					id: item.productId,
					appletType: this.$store.state.appType === this.$base.ADMIN_TYPE ? 0 : 1,
				}).then(res => {
					this.dataInfo = res.data
					this.dataId = item.id
					this.dataNum = item.productNum
					this.goodsPopShow = true
				})
			},
			// 关闭规格选择弹窗
			handleCloseGoodsWindow(current, num) {
				this.goodsPopShow = false
				if (current && current.id) {
					this.$utils.loading()
					api.post('/goods/api/ShoppingCart/updateShoppingCart', {
						id: this.dataId,
						productId: current.id,
						productNum: num
					}).then(res => {
						this.getData()
					})
				}
			},
			handleBuy() {
				this.$utils.loading()
				const details = this.dataList.reduce((arr, item) => {
					return [...arr, ...item.list.filter(item1 => !!item1.checked).map(item1 => {
						const {
							productNum: buyNum,
							brandId,
							productId,
							id: shoppingCartId
						} = item1
						return {
							buyNum,
							brandId,
							productId,
							shoppingCartId
						}
					})]
				}, [])
				if (!details.length) {
					return this.$utils.showToast('请勾选商品')
				}
				api.post('/order/api/order/preOrder', {
					preOrderType: this.goodsType,
					productDetails: details
				}).then(res => {
					console.log(res)
					if (res.data && res.data.preOrderNo) {
						uni.navigateTo({
							url: '/pages/goods/pages/confirm?order=' + res.data.preOrderNo
						})
					} else {
						this.$utils.showToast('下单失败，请重试')
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		padding-bottom: 0;
	}
</style>

<style lang="scss">
	.u-number-box__minus {
		width: 48rpx !important;
		border: 1rpx solid #CCCCCC !important;
		border-radius: 24rpx 0px 0px 24rpx !important;
	}

	.u-number-box__plus {
		width: 48rpx !important;
		border: 1rpx solid #CCCCCC !important;
		border-radius: 0px 24rpx 24rpx 0px !important;
	}

	.u-number-box__input {
		width: 48rpx !important;
		margin: 0 !important;
		border-top: 1rpx solid #CCCCCC;
		border-bottom: 1rpx solid #CCCCCC;
	}
</style>

<style lang="scss" scoped>
	.container {
		.list_item_box+.list_item_box {
			margin-top: 16rpx;
		}

		.disabled_wrap {
			.disabled_lis_box {
				transition: 0.3s all ease-in-out;
				overflow: hidden;
				transform-origin: 50% 50% 0px;
			}

			.arrow_icon {
				transition: 0.3s all ease-in-out;
			}

			&.unfold .arrow_icon {
				transform: rotate(180deg);
			}
		}

		/deep/ {
			&.u-swipe-action,
			&.u-swipe-action-item,
			&.u-swipe-action-item__content {
				width: 100%;
				display: flex;
				align-items: stretch;
			}
		}

		.swipe-action {
			&__content {
				padding: 25rpx 0;

				&__text {
					font-size: 15px;
					color: $u-main-color;
					padding-left: 30rpx;
				}
			}
		}
	}
</style>